module latextable
!dir$ nooptimize
	use myfuncs
	implicit none
	

	integer	:: myunit
	integer, parameter	:: ntextfield=35
	
	private	:: myunit

	contains
	
	subroutine savelatexboth(filename,mat1,fmt1,mat2,fmt2,header,rowname,blockname,fmat)
        character(len=*):: filename,fmt1,fmt2
        real            :: mat1(:,:), mat2(:,:)
		logical, optional	:: fmat(:,:)
		character(len=ntextfield)	:: header(:),rowname(:),blockname(:)
        integer         :: ioerr,ib,ir,j
		character(len=ntextfield)	:: cells(size(header))
		character(len=ntextfield*size(header)):: line
		
 
        open (file=filename,iostat=ioerr,newunit=myunit)
        if(ioerr/=0) then
            print *,"savemat could not open file for writing: ",filename
            stop
		endif

		line="$ \begin{tabular}{l"//repeat("r",size(mat1,2))//"}"
		write(myunit,'(a)') trim(line)
				
		write(myunit,'(a)') "\hline \hline"	
		
		cells=header
		call printcells(cells,.false.)

		do ib=1,size(blockname)
			write(line,'(a)') "\hline \multicolumn{"//convtos(size(header))//"}{c}{"//trim(blockname(ib))//"} \\ \hline"
			write(myunit,'(a)') trim(line)
			do ir=1,size(rowname)
				cells(1)=trim(rowname(ir))
				do j=1,size(mat1,2)
					if(present(fmat)) then
						if(fmat((ib-1)*size(rowname)+ir,j)) then
							write(cells(j+1),'('//fmt1//',a,'//fmt2//',a)') mat1((ib-1)*size(rowname)+ir,j),"|\textbf{",mat2((ib-1)*size(rowname)+ir,j),"}"
						else
							write(cells(j+1),'('//fmt1//',a,'//fmt2//')') mat1((ib-1)*size(rowname)+ir,j),"|",mat2((ib-1)*size(rowname)+ir,j)
					endif
					else
						write(cells(j+1),'('//fmt1//',a,'//fmt2//')') mat1((ib-1)*size(rowname)+ir,j),"|",mat2((ib-1)*size(rowname)+ir,j)
					endif
				enddo
				call printcells(cells,(ib==size(blockname) .and. ir==size(rowname)))
			enddo
        enddo
		write(myunit,'(a)') "\end{tabular}$"	
        close(myunit)
	end subroutine

	subroutine savelatex(filename,mat,fmt,header,rowname,blockname,fmat)
        character(len=*):: filename,fmt
        real            :: mat(:,:)
		logical, optional	:: fmat(:,:)
		character(len=ntextfield)	:: header(:),rowname(:),blockname(:)
        integer         :: ioerr,ib,ir,j
		character(len=ntextfield)	:: cells(size(header))
		character(len=ntextfield*size(header)):: line
		
 
        open (file=filename,iostat=ioerr,newunit=myunit)
        if(ioerr/=0) then
            print *,"savemat could not open file for writing: ",filename
            stop
		endif

		line="$ \begin{tabular}{l"//repeat("r",size(mat,2))//"}"
		write(myunit,'(a)') trim(line)
				
		write(myunit,'(a)') "\hline \hline"	
		
		cells=header
		call printcells(cells,.false.)

		do ib=1,size(blockname)
			write(line,'(a)') "\hline \multicolumn{"//convtos(size(header))//"}{c}{"//trim(blockname(ib))//"} \\ \hline"
			write(myunit,'(a)') trim(line)
			do ir=1,size(rowname)
				cells(1)=trim(rowname(ir))
				do j=1,size(mat,2)
					if(present(fmat)) then
						if(fmat((ib-1)*size(rowname)+ir,j)) then
							write(cells(j+1),'(a,'//fmt//',a)') "\textbf{",mat((ib-1)*size(rowname)+ir,j),"}"
						else
							write(cells(j+1),'('//fmt//')') mat((ib-1)*size(rowname)+ir,j)
						endif
					else
						write(cells(j+1),'('//fmt//')') mat((ib-1)*size(rowname)+ir,j)
					endif
				enddo
				call printcells(cells,(ib==size(blockname) .and. ir==size(rowname)))
			enddo
        enddo
		write(myunit,'(a)') "\end{tabular}$"	
        close(myunit)
	end subroutine

	subroutine printcells(cells,endflag)
		character(len=ntextfield)	:: cells(:)
		logical	:: endflag
		integer	:: i
		character(len=ntextfield*size(cells)):: line
		line=""
		do i=1,size(cells)
			write(line((i-1)*ntextfield+1:i*ntextfield),'(a)') trim(cells(i))//merge(merge("  ","\\",endflag)," &",i==size(cells))
		enddo
		write(myunit,'(a)') trim(line)
	
	end subroutine
	
end module	
	
	
module ssmaster
!dir$ nooptimize
	use compute
	use hmdamod
	use ssmean
	use sscluster
	use latextable
	implicit none
	
	
	contains
	
	subroutine printlables(labels)
		character(len=*)	:: labels(:)
		integer	:: n,k,i
		character(len=size(labels)*len(labels))	:: line
		n=size(labels)
		k=len(labels)
		do i=1,n
			write(line((i-1)*k+1:i*k),'(a)') labels(i)
		enddo
		write (*,'(a)') " "//line
	end subroutine
	
	function fname(k,n0) result(val)
		integer				:: k,n0
		character(len=50)	:: val
		val="_"//convtos(k)//"_"//convtos(n0)//"_"//convtos(nint(100*level))
	end function

	subroutine saveclustempMC
		integer	:: nlist(3)=[50,100,200]
		real, allocatable	:: crl(:,:),arl(:,:,:)
		integer	:: in,j

		do clustertype=0,0
		stage=2		
		call loadlam
		do in=1,size(nlist)
			n_sample=nlist(in)
			call init_std_mean
			ic=0
			do
				if(ssclust_data(crl)) then
					if(ic==1) then
						allocate(arl(size(crl,1),size(crl,2),1))
						arl(:,:,1)=crl
					else
						arl=reshape([arl,crl],[size(crl,1),size(crl,2),size(arl,3)+1])
					endif
					call mdisp(arl(1,:,ic:1:-1))
					call mdisp(arl(2,:,ic:1:-1))
					call mdisp(arl(3,:,ic:1:-1))
					print *,ic
				else
					exit
				endif
				call printtime
				print *,ic
			enddo
			print *,"done with n=",n_sample
			call mdisp(arl(1,:,:))
			call mdisp(arl(2,:,:))
			call mdisp(arl(3,:,:))
			if(clustertype==0) then
				if(FE) then
					call savemat(trim(folder)//"empMCclustFEX"//convtos(n_sample)//trim(fname(k,n0))//".txt",arl(1,:,:).cud.arl(2,:,:).cud.arl(3,:,:))
				else
					call savemat(trim(folder)//"empMCclust"//convtos(n_sample)//trim(fname(k,n0))//".txt",arl(1,:,:).cud.arl(2,:,:).cud.arl(3,:,:))
				endif
			else
				call savemat(trim(folder)//"empMCclust_union"//convtos(n_sample)//trim(fname(k,n0))//".txt",arl(1,:,:).cud.arl(2,:,:).cud.arl(3,:,:))
			endif
			deallocate(arl)
		enddo
		enddo
	end subroutine
	
	subroutine saveempMCtwosamples
		integer	:: nlist(3)=[50,100,500]
		real, allocatable	:: crl(:,:),arl(:,:,:)
		integer	:: in,j
	
		stage=2		
		call loadlam
		do in=1,size(nlist)
			n_sample=nlist(in)
			call init_2s
			ic=0
			do
				if(sstwosample(crl)) then
					if(ic==1) then
						allocate(arl(size(crl,1),size(crl,2),1))
						arl(:,:,1)=crl
					else
						arl=reshape([arl,crl],[size(crl,1),size(crl,2),size(arl,3)+1])
					endif
					call mdisp(arl(1,:,ic:1:-1))
					call mdisp(arl(2,:,ic:1:-1))
					call mdisp(arl(3,:,ic:1:-1))
					print *,ic
				else
					exit
				endif
			enddo
			print *,"done with n=",n_sample
			call mdisp(arl(1,:,:))
			call mdisp(arl(2,:,:))
			call mdisp(arl(3,:,:))
			call savemat(trim(folder)//"emptwosamples"//convtos(n_sample)//trim(fname(k,n0))//".txt",arl(1,:,:).cud.arl(2,:,:).cud.arl(3,:,:))
			deallocate(arl)
		enddo
	end subroutine
	
	subroutine saveempMC
		integer	:: nlist(3)=[50,100,500]
		real, allocatable	:: crl(:,:),arl(:,:,:)
		integer	:: in,j
	
		stage=2		
		call loadlam
		do in=1,size(nlist)
			n_sample=nlist(in)
			call init_std_mean
			ic=0
			do
				if(ssdata(crl)) then
					if(ic==1) then
						allocate(arl(size(crl,1),size(crl,2),1))
						arl(:,:,1)=crl
					else
						arl=reshape([arl,crl],[size(crl,1),size(crl,2),size(arl,3)+1])
					endif
					call mdisp(arl(1,:,ic:1:-1))
					call mdisp(arl(2,:,ic:1:-1))
					call mdisp(arl(3,:,ic:1:-1))
					print *,ic
				else
					exit
				endif
			enddo
			print *,"done with n=",n_sample
			call mdisp(arl(1,:,:))
			call mdisp(arl(2,:,:))
			call mdisp(arl(3,:,:))
			call savemat(trim(folder)//"empMC"//convtos(n_sample)//trim(fname(k,n0))//".txt",arl(1,:,:).cud.arl(2,:,:).cud.arl(3,:,:))
			deallocate(arl)
		enddo
	end subroutine
	
	subroutine mkMCtable
		integer	:: nlist(4)=[25,50,100,500]
		real, allocatable	:: crl(:,:)
		character(len=ntextfield)	:: header(8)=["","N(0,1)","LogN","F(4,5)","\ \ t(3)","P(0.4)","Mix 1","Mix 2"]
		character(len=ntextfield)	:: rowname(4)=["\textsc{t-stat}","\textsc{sym-boot}","\textsc{asym-boot}","\textsc{new default}"]
		character(len=ntextfield)	:: blockname(3)=["$n=50$","$n=100$","$n=500$"]
		real	:: tab(16,7,3)
		integer	:: in,j
	
		stage=2		
		call loadlam
		tab=-1
		do in=1,size(nlist)
			n_sample=nlist(in)
			if(n_sample<3*k) then
				tab((in-1)*4+1:in*4,:,:)=0
				cycle
			endif
			call init_std_mean
			ic=0
			do
				if(ssMC(crl)) then
					do j=1,3
						tab((in-1)*4+1:in*4,ic,j)=crl(j,1:4)
					enddo
				else
					exit
				endif
				if(ic==7) exit
			enddo
			print *,"done with n=",n_sample
			call mdisp(tab(:,:,1))
			call mdisp(tab(:,:,2))
		enddo
		call savemat(trim(folder)//"MCRP"//trim(fname(k,n0))//".txt",tab(:,:,1).cud.tab(:,:,2).cud.tab(:,:,3))
		call savelatexboth(trim(folder)//"MC_"//trim(fname(k,n0))//".tex",100*tab(5:,:,1),"F4.1",tab(5:,:,2),"F4.2",header,rowname,blockname,tab(5:,:,1)<level+0.01)
	end subroutine

	subroutine mkMCktable
		integer	:: nlist(4)=[25,50,100,500]
		integer	:: klist(4)=[8,4,12,-99], mk, n0x
		real, allocatable	:: crl(:,:)
		character(len=ntextfield)	:: header(8)=["","N(0,1)","LogN","F(4,5)","\ \ t(3)","P(0.4)","Mix 1","Mix 2"]
		character(len=ntextfield)	:: rowname(4)=["\textsc{def}: $k=8,n_{0}=50$}","$k=4, n_{0}=50$","$k=12, n_{0}=50$","$k=4, n_{0}=25$"]
		character(len=ntextfield)	:: blockname(4)=["$n=25$","$n=50$","$n=100$","$n=500$"]
		real	:: tab(16,7,3)
		real, allocatable	:: mdata(:,:)
		integer	:: in,j,ik
	
		tab=-1
		do ik=1,size(klist)
			mk=klist(ik)
			if(mk>0) then
				n0x=50
			else
				mk=4
				n0x=25
			endif
			mdata=loadmat(trim(folder)//"MCRP"//trim(fname(mk,n0x))//".txt")
			do in=1,size(nlist)
				do j=1,3
					tab(4*(in-1)+ik,:,j)=mdata((j-1)*16+4*(in-1)+4,:)
				enddo
			enddo
			call mdisp(tab(:,:,1))
			call mdisp(tab(:,:,2))
		enddo
		call savelatexboth(trim(folder)//"MC_k_"//convtos(nint(100*level))//".tex",100*tab(:,:,1),"F4.1",tab(:,:,2),"F4.2",header,rowname,blockname,tab(:,:,1)<level+0.01)
	end subroutine

	subroutine mkMCclustertable
		integer	:: nlist(3)=[50,100,500]
		real, allocatable	:: crl(:,:)
		character(len=ntextfield)	:: header(8)=["","N(0,1)","LogN","F(4,5)","\ \ t(3)","P(0.4)","Mix 1","Mix 2"]
		character(len=ntextfield)	:: rowname(4)=["\textsc{STATA}","\textsc{Im-Ko}","\textsc{CGM}","\textsc{new default}"]
		character(len=ntextfield)	:: blockname(3)=["$n=50$","$n=100$","$n=500$"]
		real	:: tab(12,7,3)
		integer	:: in,j
	
		stage=2		
		call loadlam
		tab=-1
		do in=1,size(nlist)
			n_sample=nlist(in)
			call init_std_mean
			ic=0
			do
				if(ssclust_MC(crl)) then
					do j=1,3
						tab((in-1)*4+1:in*4,ic,j)=crl(j,[1,3,4,5])
					enddo
				else
					exit
				endif
				if(ic==7) exit
			enddo
			print *,"done with n=",n_sample
			call mdisp(tab(:,:,1))
			call mdisp(tab(:,:,2))
		enddo
		call savelatexboth(trim(folder)//"MCclust"//trim(fname(k,n0))//".tex",100*tab(:,:,1),"F4.1",tab(:,:,2),"F4.2",header,rowname,blockname,tab(:,:,1)<level+0.01)
	end subroutine

	subroutine mkMC2Stable
		integer	:: nlist(3)=[50,100,500]
		real, allocatable	:: crl(:,:)
		character(len=ntextfield)	:: header(8)=["","N(0,1)","LogN","F(4,5)","\ \ t(3)","P(0.4)","Mix 1","Mix 2"]
		character(len=ntextfield)	:: rowname(4)=["\textsc{t-stat}","\textsc{sym-boot}","\textsc{asym-boot}","\textsc{new default}"]
		character(len=ntextfield)	:: blockname(3)=["$n=50$","$n=100$","$n=500$"]
		real	:: tab(12,7,3)
		integer	:: in,j
	
		stage=2		
		call loadlam
		tab=-1
		do in=1,size(nlist)
			n_sample=nlist(in)
			call init_2s
			ic=0
			do
				if(ssMC2S(crl)) then
					do j=1,3
						tab((in-1)*4+1:in*4,ic,j)=crl(j,1:4)
					enddo
				else
					exit
				endif
				if(ic==7) exit
			enddo
			print *,"done with n=",n_sample
			call mdisp(tab(:,:,1))
			call mdisp(tab(:,:,2))
		enddo
		call savelatexboth(trim(folder)//"MC2S_"//trim(fname(k,n0))//".tex",100*tab(:,:,1),"F4.1",tab(:,:,2),"F4.2",header,rowname,blockname,tab(:,:,1)<level+0.01)
	end subroutine

	subroutine evalss
		integer	:: i
		character(len=10)	:: anames(500)
		real, allocatable	:: crl(:,:),arl(:,:,:)
	
		print *,"enter evalss with n=",n_sample
		call init_std_mean
		anames=""		
		ic=0
		do
			if(ssMC(crl)) then
				if(ic==1) then
					allocate(arl(size(crl,1),size(crl,2),1))
					arl(:,:,1)=crl
				else
					arl=reshape([arl,crl],[size(crl,1),size(crl,2),size(arl,3)+1])
				endif
				anames(ic)=cname
			else
				exit
			endif
		enddo
		print *,"n=",n_sample
		call printlables(anames(1:ic-1))
		call mdisp(arl(1,:,:))
		call mdisp(arl(2,:,:))
	end subroutine
end module
	
